package com.judysen.jsqlweb.controller;

import com.alibaba.fastjson.JSON;
import com.judysen.jsqlweb.aop.JsqlLoggerAnnotation;
import com.judysen.jsqlweb.models.DatabaseConfigModel;
import com.judysen.jsqlweb.models.RestResult;
import com.judysen.jsqlweb.services.DatabaseConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/config")
public class DatabaseConfigController {
    private Logger logger = LoggerFactory.getLogger(DatabaseConfigController.class);
    @Resource(name = "databaseConfigService")
    private DatabaseConfigService configService;

    @JsqlLoggerAnnotation
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public RestResult saveConfig(@RequestBody DatabaseConfigModel model) {
        logger.info(String.format("saveConfig start,[%s]", JSON.toJSONString(model)));
        //1---将配置写入数据库----
        configService.save(model);
        //2---将新配置记入DynamicDatabase中
        var result = new RestResult(200, "", 1);
        logger.info(String.format("saveConfig end,[%s]", JSON.toJSONString(result)));
        return result;
    }

    @JsqlLoggerAnnotation
    @RequestMapping(method = RequestMethod.PUT)
    @ResponseBody
    public RestResult updateConfig(@RequestBody DatabaseConfigModel model) {
        configService.update(model);
        var result = new RestResult(200, "", 1);
        return result;
    }

    @JsqlLoggerAnnotation
    @RequestMapping(method = RequestMethod.GET)
    public RestResult getConfigs() {
        var configs = configService.getAllConfigs();
        var result = new RestResult(200, "", configs);
        return result;
    }
    @JsqlLoggerAnnotation
    @GetMapping("/display_name")
    public RestResult getAllDisplayNames() {
        var displayNames = configService.getAllDisplayName();
        return new RestResult(200, "", displayNames);
    }
}
